package com.benyq.networkprogramme.tcp

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import com.benyq.networkprogramme.udp.UDPServer

class TcpService : Service() {

    private lateinit var tcpReceiver:TcpReceiver
    private var tcpSender: TcpSender? = null

    override fun onBind(intent: Intent): IBinder {
        val ip = intent.getStringExtra("ipAddress")
        val port = intent.getIntExtra("port", -1)
//        val ip = "0.0.0.0"
//        val port = 8388
        if (ip != null && port != -1){
            tcpSender = TcpSender(ip, port)
            tcpSender?.sendMsg("我是你爸爸")
        }
        Log.e("susan", "onStartCommand")
        return TcpServiceBinder()
    }

    override fun onCreate() {
        super.onCreate()
        tcpReceiver = TcpReceiver(8388)
        //UDPServer.startServer()
        Log.e("susan", "onCreate")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        return super.onStartCommand(intent, flags, startId)
    }

    override fun onUnbind(intent: Intent?): Boolean {
        return super.onUnbind(intent)
    }

    override fun onDestroy() {
        Log.e("susan", "onDestroy")
        super.onDestroy()
    }

    inner class TcpServiceBinder: Binder(){

        fun sendMessage(msg:String){
            tcpSender?.sendMsg(msg)
        }

        fun isConnectd(): Boolean{
            return tcpSender != null
        }

    }





}
